import 'dart:io';

import 'package:amoy_ticket/people/people_main/people_main_logic.dart';
import 'package:amoy_ticket/utils/photo_view_screen/fade_route.dart';
import 'package:amoy_ticket/utils/photo_view_screen/photo_view_gallery_screen.dart';
import 'package:amoy_ticket/utils/photo_view_screen/photo_view_simple_screen.dart';
import 'package:amoy_ticket/utils/router/getRouteConfig.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
// import 'package:url_launcher/url_launcher.dart';

class PeopleMainPage extends StatefulWidget {
  PeopleMainPage({Key? key}) : super(key: key);

  @override
  _PeopleMainPageState createState() => _PeopleMainPageState();
}

class _PeopleMainPageState extends State<PeopleMainPage> {
  final logic = Get.put(PeopleMainLogic());

  @override
  void initState() {
    // logic.scrollListener();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<PeopleMainLogic>(
      builder: (logic) => Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          toolbarHeight: 40,
          title: Text(
            '我的',
            style: TextStyle(color: Colors.black.withOpacity(logic.opacity)),
          ),
          elevation: logic.opacity > 0.8 ? 0.5 : 0,
          backgroundColor:
              logic.opacity > 0.8 ? Colors.white : Color(0xFFf5f6f8),
          actions: [
            GestureDetector(
              onTap: () {
                Navigator.of(context).push(new FadeRoute(
                    page: PhotoViewGalleryScreen(
                  images: logic.imgUrlList, //传入图片list
                  // index: index, 传入当前点击的图片的index
                  index: 0,
                )));
              },
              child: Image.asset(
                'assets/images/message_icon.png',
                height: 21.w,
                width: 21.w,
                color: Colors.black.withOpacity(logic.opacity),
              ),
            ),
            SizedBox(width: 20.w),
            GestureDetector(
              onTap: () {
                Get.toNamed(RouteConfig.useSmartDialog);
              },
              child: GestureDetector(
                child: Image.asset(
                  'assets/images/setting_icon.png',
                  height: 21.r,
                  width: 21.r,
                  color: Colors.black.withOpacity(logic.opacity),
                ),
              ),
            ),
            SizedBox(width: 20.w),
          ],
        ),
        backgroundColor: Color(0xFFf5f6f8),
        body: SingleChildScrollView(
          controller: logic.scrollController,
          child: Stack(
            children: [
              Container(
                width: MediaQuery.of(context).size.width,
                height: 150,
                // decoration: BoxDecoration(
                //   image: DecorationImage(
                //       image: AssetImage('assets/images/people_bg.png'),
                //       fit: BoxFit.fill),
                // ),
              ),
              Container(
                padding: EdgeInsets.only(
                    // top: MediaQuery.of(context).padding.top + 20.h,
                    left: 20.w,
                    right: 20.w),
                child: Column(
                  children: [
                    Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              GestureDetector(
                                onTap: () {
                                  // 单张图片大图显示
                                  Navigator.of(context).push(
                                    new FadeRoute(
                                      page: PhotoViewSimpleScreen(
                                        imageUrl: logic.headImg.value,
                                        heroTag: 'simple',
                                        imageProvider: null,
                                      ),
                                    ),
                                  );
                                },
                                onLongPress: () {
                                  logic.chooseheadImg(context);
                                },
                                child: CircleAvatar(
                                  radius: 22.r,
                                  backgroundImage: CachedNetworkImageProvider(
                                    logic.headImg.value,
                                  ),
                                ),
                              ),
                              SizedBox(width: 20.w),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  GestureDetector(
                                    onTap: () {
                                      _clickTitleMethod();
                                    },
                                    child: Row(
                                      children: [
                                        Text(
                                          logic.userName.value,
                                          style: TextStyle(
                                              fontSize: 18.sp,
                                              color: Colors.black,
                                              fontWeight: FontWeight.w600),
                                        ),
                                        SizedBox(width: 5.w),
                                        Icon(
                                          Icons.warning_amber,
                                          color: Colors.black,
                                          size: 15.sp,
                                        ),
                                      ],
                                    ),
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      _richText('关注', 0),
                                      SizedBox(width: 10.w),
                                      _richText('粉丝', 0),
                                    ],
                                  )
                                ],
                              )
                            ],
                          ),
                          Row(
                            children: [
                              GestureDetector(
                                onTap: () {
                                  Navigator.of(context).push(new FadeRoute(
                                      page: PhotoViewGalleryScreen(
                                    images: logic.imgUrlList, //传入图片list
                                    // index: index, 传入当前点击的图片的index
                                    index: 0,
                                    // heroTag: img, //传入当前点击的图片的hero tag （可选）
                                  )));
                                },
                                child: Image.asset(
                                  'assets/images/message_icon.png',
                                  height: 21.w,
                                  width: 21.w,
                                ),
                              ),
                              SizedBox(width: 20.w),
                              GestureDetector(
                                onTap: () {
                                  Get.toNamed(RouteConfig.useSmartDialog);
                                },
                                child: GestureDetector(
                                  child: Image.asset(
                                    'assets/images/setting_icon.png',
                                    height: 21.r,
                                    width: 21.r,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 30.h),
                    GestureDetector(
                      onTap: () {
                        Get.toNamed(RouteConfig.vipMainPage);
                      },
                      child: Image.asset('assets/images/vip_bg.png'),
                    ),
                    SizedBox(height: 10.h),
                    Container(
                      padding: EdgeInsets.symmetric(vertical: 15.h),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10.r),
                        color: Colors.white,
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          _iconWidget(
                              'assets/images/movie_active_icon.png', '电影票',
                              color: Color(0xFFfe3971), callBack: () {
                            Get.toNamed(RouteConfig.cinemaTicketPage);
                          }),
                          _iconWidget(
                            'assets/images/snack_icon.png',
                            '小食周边',
                            color: Color(0xFFfaa123),
                            callBack: () {
                              SmartDialog.compatible.show(
                                widget: Container(
                                  padding: EdgeInsets.all(50),
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(20),
                                  ),
                                  width: 250,
                                  child: Column(
                                    mainAxisSize: MainAxisSize.min,
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      _launchURL(
                                          'tel:+86 182-5190-2024', '打开电话'),
                                      _launchURL(
                                          'sms:+86 182-5190-2024', '发送短信'),
                                      _launchURL(
                                          Platform.isAndroid
                                              ? 'sms:+86 182-5190-2024?body=业精于勤荒于嬉，行成于思毁于随。'
                                              : Platform.isIOS
                                                  ? 'sms:86 182-5190-2024&body=业精于勤荒于嬉，行成于思毁于随。'
                                                  : '',
                                          '发送短信2'),
                                      _launchURL(
                                          'https://qjmykb-oss-test.oss-cn-shanghai.aliyuncs.com/documents/20210914/小步阅读计划4.0手册S12.pdf',
                                          '打开地图'),
                                    ],
                                  ),
                                ),
                              );
                            },
                          ),
                          _iconWidget(
                              'assets/images/perform_active_icon.png', '演出票',
                              color: Color(0xFFa554f7)),
                        ],
                      ),
                    ),
                    SizedBox(height: 10),
                    Container(
                      padding: EdgeInsets.only(top: 10.h, bottom: 40.h),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        color: Colors.white,
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            margin: EdgeInsets.only(left: 15, bottom: 10),
                            child: Text(
                              '我的服务',
                              style: TextStyle(
                                  fontSize: 15.sp, fontWeight: FontWeight.w600),
                            ),
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              _iconWidget(
                                  'assets/images/coupon_icon.png', '优惠券',
                                  callBack: () =>
                                      Get.toNamed(RouteConfig.couponPage)),
                              _iconWidget(
                                  'assets/images/cinema_card_icon.png', '权益卡',
                                  callBack: () =>
                                      Get.toNamed(RouteConfig.equityCardPage)),
                              _iconWidget(
                                  'assets/images/gift_card_icon.png', '乐影卡',
                                  callBack: () {
                                Get.toNamed(RouteConfig.musicAndMovieCardPage);
                              }),
                              _iconWidget('assets/images/more_icon.png', '更多服务',
                                  callBack: () {
                                Get.toNamed(RouteConfig.moreServicePage);
                              }),
                            ],
                          )
                        ],
                      ),
                    ),
                    SizedBox(height: 10.h),
                    GestureDetector(
                      onTap: () {
                        Get.toNamed(RouteConfig.webviewPage, arguments: {
                          'url':
                              'https://t.taopiaopiao.com/yep/page/m/yptabym?sqm=dianying.dy.home.tabbar.MinePageBanner_d3787c09c137a7e0&cityCode=320100&spm=a2115o.8783827.0.0',
                          'title': '少年的青春与成长'
                        });
                      },
                      child: Image.asset('assets/images/people_bg_two.png'),
                    ),
                    SizedBox(height: 10.h),
                    GestureDetector(
                      child: Image.asset('assets/images/people_bg_three.png'),
                    ),
                    SizedBox(height: 20.h),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _launchURL(String url, String label) {
    return ElevatedButton(
      child: Text(label),
      onPressed: () async {
        final uri = Uri.parse(url);
        // Android 谷歌地图的 scheme , 后面是北京市海淀区的经纬度
        // const url = 'geo:116.3,39.95';
        // const url = 'tel:+86 182-5190-2024';
        // const url = 'sms:+86 182-5190-2024';
        // if (await canLaunchUrl(uri)) {
        //   // Android 手机, 打开 Google 地图
        //   await launchUrl(
        //     uri,
        //   );
        // }
        // await launch(url, forceWebView: true);
        // else {
        //   // 如果安卓手机打不开说明是苹果手机
        //   final urlIos = Uri.parse('http://maps.apple.com/?ll=116.3,39.95');
        //   if (await canLaunchUrl(urlIos)) {
        //     await launchUrl(urlIos);
        //   } else {
        throw 'Could not launch $url';
        //   }
        // }
      },
    );
  }

  Widget _richText(String label, int num) {
    return RichText(
      text: TextSpan(
          text: label,
          style: TextStyle(
            color: Colors.grey,
            fontSize: 13.sp,
          ),
          children: [
            TextSpan(text: '  '),
            TextSpan(
              text: num.toString(),
              style: TextStyle(
                color: Colors.black,
                // fontWeight: FontWeight.bold,
                fontSize: 11.sp,
              ),
            ),
          ]),
    );
  }

  Widget _iconWidget(String imageUrl, String label,
      {Function()? callBack, Color? color}) {
    return GestureDetector(
      onTap: callBack,
      child: Column(
        children: [
          Image.asset(
            imageUrl,
            width: 28.w,
            height: 28.w,
            color: color,
          ),
          Text(label),
        ],
      ),
    );
  }

  void _clickTitleMethod() {
    String name = logic.userName.value.replaceRange(
        1,
        logic.userName.value.length - 1,
        '*' * (logic.userName.value.length - 2));
    SmartDialog.compatible.showAttach(
      targetContext: context,
      isPenetrateTemp: true,
      target: Offset(-10.w, 140.w),
      alignmentTemp: Alignment.topCenter,
      widget: Container(
        width: 210.w,
        padding: EdgeInsets.all(5.w),
        decoration: BoxDecoration(
          color: Color(0xFFebad63),
          boxShadow: [
            BoxShadow(color: Colors.black12, blurRadius: 8, spreadRadius: 0.2)
          ],
        ),
        child: RichText(
          text: TextSpan(
            text: '为保护购物隐私，你的淘宝昵称在影评等公共区域，将显示为“$name”，想要展现完整昵称，可以 ',
            style: TextStyle(fontSize: 11.sp),
            children: [
              TextSpan(
                text: '设置淘票票昵称',
                style: TextStyle(fontSize: 11.sp, fontWeight: FontWeight.bold),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    SmartDialog.dismiss();
                    Get.toNamed(RouteConfig.modifyNickNamePage)!.then(
                      (value) => logic.getNickName(),
                    );
                  },
              ),
            ],
          ),
        ),
      ),
    );
  }
}
